﻿using Model;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utility;

namespace DataProvider
{
    public class Sys_DeptProvider
    {
        public static readonly Sys_DeptProvider Instances = new Sys_DeptProvider();
        public static readonly Sys_DeptService Service = Sys_DeptService.Instances;
        public static readonly Sys_UserService UserService = Sys_UserService.Instances;

        public List<Sys_Dept> GetTreeList()
        {
            var List = Service.QueryCustom(" Status=0 ").OrderBy(x=>x.SortCode).ToList();
            if (List.Any())
            {
                var allUserList = UserService.GetAllList();
                List.ForEach(x => {
                    x.ManagerName = allUserList.FirstOrDefault(a => a.Id == x.ManagerId)?.EnglishName;
                });
            }
            var TopList = List.FindAll(x => x.ParentId == 0);
            foreach(var d in TopList)
            {
                var isPid = d.ParentId != d.Id && d.ParentId > 0;
                d.children = List.FindAll(x => x.ParentId == d.Id && isPid);
                if (d.children != null && d.children.Count > 0)
                {
                    d.isParent = true;
                    foreach (var children in d.children)
                    {
                        BuildChildren(children, List);
                    }
                }
                else {
                    d.isParent = false;
                }
            }
            return TopList;
            void BuildChildren(Sys_Dept d, List<Sys_Dept> allList)
            {
                var isPid = d.ParentId != d.Id && d.ParentId > 0;
                d.children = List.FindAll(x => x.ParentId == d.Id && isPid);
                if (d.children != null && d.children.Count > 0)
                {
                    d.isParent = true;
                    foreach (var children in d.children)
                    {
                        BuildChildren(children, List);
                    }
                }
                else
                {
                    d.isParent = false;
                }
            }
        }
    }
}
